<template>
  <el-card class="box-card">
    <!-- 标题 -->
    <div slot="header" class="clearfix">
      <span>文章列表</span>
    </div>
    <!-- 搜索区域  |  发表文章按钮-->
    <div class="search-box">
      <!-- 左边 搜索区域 -->
      <el-form :inline="true" :model="query">
        <el-form-item label="文章分类">
          <el-select
            v-model="query.cate_id"
            placeholder="请选择分类"
            size="small"
          >
            <el-option
              v-for="sel in cateList"
              :key="sel.id"
              :label="sel.cate_name"
              :value="sel.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发布状态" style="margin-left: 15px">
          <el-select
            v-model="query.state"
            placeholder="请选择状态"
            size="small"
          >
            <el-option label="已发布" value="已发布"></el-option>
            <el-option label="草稿" value="草稿"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="getArticleList()" type="primary" size="small"
            >筛选</el-button
          >
          <el-button @click="resetSearth()" type="info" size="small"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <!--右边  发表文章的按钮 -->
      <el-button
        @click="showPub = true"
        type="primary"
        size="small"
        class="btn-pub"
        >发表文章</el-button
      >
    </div>

    <!-- 文章表格区域 -->
    <el-table :data="articleList" style="width: 100%" border>
      <el-table-column label="文章标题" prop="title">
        <template #default="{ row }">
          <el-link @click="lookDetail(row.id)" type="primary">
            {{ row.title }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="分类" prop="cate_name"></el-table-column>
      <el-table-column label="发表时间">
        <template #default="{ row }">{{ formatTime(row.pub_date) }}</template>
      </el-table-column>
      <el-table-column label="状态" prop="state"></el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="danger" @click="delArticle(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页区域 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="query.pagenum"
      :page-sizes="[2, 3, 5, 10]"
      :page-size="query.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
    <!-- 发表文章弹出层 -->
    <el-dialog
      title="发表文章"
      fullscreen
      :visible.sync="showPub"
      :before-close="closePub"
      @close="closeDialog"
    >
      <!-- 发布文章的对话框 -->
      <el-form
        :model="pubForm"
        :rules="pubFormRules"
        ref="pubFormRef"
        label-width="100px"
      >
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="pubForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="cate_id">
          <el-select
            v-model="pubForm.cate_id"
            placeholder="请选择分类"
            style="width: 100%"
          >
            <el-option
              v-for="sel in cateList"
              :key="sel.id"
              :label="sel.cate_name"
              :value="sel.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章封面">
          <!-- 用来显示封面的图片 -->
          <img
            :src="previewUrl || defImg"
            alt=""
            class="cover-img"
            ref="imgRef"
          />
          <br />
          <!-- 文件选择框，默认被隐藏 -->
          <input
            @change="previewImg"
            type="file"
            hidden
            accept="image/*"
            ref="selInput"
          />
          <!-- 选择封面的按钮 -->
          <el-button @click="chooseImg" type="text">+ 选择封面</el-button>
        </el-form-item>
        <!-- 富文本编辑器 -->
        <el-form-item label="文章内容" prop="content">
          <quill-editor v-model="pubForm.content"></quill-editor>
        </el-form-item>
        <!--操作按钮  -->
        <el-form-item>
          <el-button type="primary" @click="publish('已发布')">发布</el-button>
          <el-button type="info" @click="publish('草稿')">草稿</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="文章弹层" :visible.sync="showDetail">
      <h1>{{ detail.title }}</h1>
      <div class="info">
        <span>作者 :{{ detail.cate_name }}</span>
        <span>发布时间 :{{ formatTime(detail.pub_date) }}</span>
        <span>文章分类 :{{ detail.state }}</span>
        <hr />
        <p>
          <img :src="`${baseURL}${detail.cover_img}`" alt="" />
        </p>
        <div class="constent" v-html="detail.content"></div>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import { getCateApi, publishArticleApi, getArticleApi, getDetailApi, delArticleApi } from '@/api/article'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import { quillEditor } from 'vue-quill-editor'
import defImg from '@/assets/images/cover.jpg'
import { formatTime } from '@/utils'
import { baseURL } from '@/utils/request'
export default {
  name: 'ArtList',
  components: {
    // 注册富文本编辑器组件
    quillEditor
  },
  data () {
    return {
      baseURL,
      showDetail: false,
      detail: {},
      articleList: [],
      showPub: false,
      previewUrl: '',
      defImg,
      cover_img: null,
      // 表单的数据对象
      pubForm: {
        title: '',
        cate_id: '',
        // 文章内容
        content: '',
        state: ''
      },
      // 文章分类
      cateList: [],
      // 表单的验证规则对象
      pubFormRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 1, max: 30, message: '文章标题的长度为1-30个字符', trigger: 'blur' }
        ],
        cate_id: [{ required: true, message: '请选择文章标题', trigger: 'blur' }],
        content: [{ required: true, message: '请输入文章内容...', trigger: 'blur' }]
      },
      total: 0,
      // 查询参数对象
      // query
      query: {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      }
    }
  },
  created () {
    this.getCateList()
    this.getArticleList()
  },
  methods: {
    async delArticle (row) {
      try {
        await this.$confirm(`确定删除：${row.title}吗？`)
        await delArticleApi(row.id)
        this.$message.success('删除成功')
        if (this.articleList.length === 1 && this.query.pagenum > 1) {
          this.query.pagenum--
        }
        this.getArticleList()
      } catch (error) {

      }
    },
    async lookDetail (id) {
      const { data } = await getDetailApi(id)
      console.log('当前点击要查看的文章详情数据 :', data)
      this.detail = data.data
      this.showDetail = true
    },
    resetSearth () {
      this.query = {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      }
      this.getArticleList()
    },
    handleSizeChange (currSize) {
      console.log('最新每页显示条数:', currSize)
      this.query.pagesize = currSize
      this.query.pagenum = 1
      this.getArticleList()
    },
    handleCurrentChange (currPage) {
      this.query.pagenum = currPage
      this.getArticleList()
    },
    formatTime,
    async getArticleList () {
      const { data } = await getArticleApi(this.query)
      console.log(data)
      this.articleList = data.data
      this.total = data.total
    },
    publish (state) {
      this.$refs.pubFormRef.validate(async (isOk) => {
        if (isOk) {
          if (!this.pubForm.cover_img) return this.$message.error('请选择文章封面')
          this.pubForm.state = state
          console.log('发布文章的表单数据:', this.pubForm)

          const fd = new FormData()
          for (const key in this.pubForm) {
            fd.append(key, this.pubForm[key])
          }
          await publishArticleApi(fd)
          this.$message.success(`发布文章${state}成功`)
          this.showPub = false
          this.getArticleList()
        }
      })
    },
    closeDialog () {
      this.$refs.pubFormRef.resetFields()
      this.previewUrl = ''
      this.pubForm.cover_img = null
      this.$refs.selInput.value = null
    },
    chooseImg () {
      this.$refs.selInput.click()
    },
    previewImg (e) {
      const files = e.target.files
      if (files.length) {
        this.previewUrl = URL.createObjectURL(files[0])
        this.pubForm.cover_img = files[0]
      }
    },
    async getCateList () {
      const { data } = await getCateApi()
      console.log('文章分类:', data)
      this.cateList = data.data
    },

    async closePub (done) {
      try {
        await this.$confirm('确定关闭发布文章的弹层吗?数据可能会丢失!')
        done()
      } catch (error) {
        console.log('点击取消关闭')
      }
    }
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}

.info {
  span {
    margin-right: 50px;
  }
}
// 设置图片封面的宽高
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}
/deep/ .ql-editor {
  min-height: 300px;
}
/deep/ .ql-toolbar .ql-snow .ql-formats {
  line-height: normal;
}

.el-pagination {
  margin-top: 15px;
}
/deep/ .el-icon-arrow-left:before,
/deep/ .el-icon-arrow-right:before {
  color: black;
}
</style>
